$(function () {
    init_spare_list();
    init_shop_list();
    devise_product();
});

function init_shop_list() {
    $.ajax({
        url: '/products-list-onshop?color-filter=_all&size-filter=_all',
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                var result_list = new Array(data.result);
                result_list.forEach((value, _idx, _arr) => {
                    value.forEach((sub_value, _sub_idx, _sub_arr) => {
                        $s_body = `
                            <tr>
                                <td>${sub_value['id']}</td>
                                <td>${sub_value['name']}</td>
                                <td>${sub_value['color']} ${sub_value['size']}</td>
                                <td>${sub_value['price']}</td>
                                <td>
                                    <button class="btn btn-danger btn-sm getoff-button" uid="${sub_value['id']}">下架</button>
                                    <!-- <button class="btn btn-success btn-sm select-button" uid="${sub_value['id']}">查看</button> -->
                                </td>
                            </tr>
                        `;
                        $('#shoping-table-body').append($s_body);
                    });
                });
                getoffshop();
            } else {
                alert('获取商品数据失败，请检查后台重试');
            }
        }
    });
    $.ajax({
        url: '/products-list-not-onshop',
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                var result_list = new Array(data.result);
                result_list.forEach((value, _idx, _arr) => {
                    value.forEach((sub_value, _sub_idx, _sub_arr) => {
                        $s_body = `
                            <tr>
                                <td>${sub_value['id']}</td>
                                <td>${sub_value['name']}</td>
                                <td>${sub_value['color']} ${sub_value['size']}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm onshop-button" uid="${sub_value['id']}">上架</button>
                                    <button class="btn btn-danger btn-sm delete-button" uid="${sub_value['id']}">删除</button>
                                    <!-- <button class="btn btn-success btn-sm select-button" uid="${sub_value['id']}">查看</button> -->
                                </td>
                            </tr>
                        `;
                        $('#waiting-table-body').append($s_body);
                    });
                });
                onshop();
                delete_product();
            } else {
                alert('获取商品数据失败，请检查后台重试');
            }
        }
    });
}

function add_product() {
    $('#add-button').click(function () {
        $('#add-Modal').modal('show');
    });
    $('#add-confirm').click(() => {
        if ($('#add-name').val() != '' && $('#add-price').val() != '' && $('#add-image').val() != '' && $('#add-num').val() != '') {
            $.ajax({
                url: '/add-product',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    name: $('#add-name').val(),
                    price: $('#add-price').val(),
                    image: $('#add-image').val().substring($('#add-image').val().lastIndexOf('\\') + 1,),
                    num: $('#add-num').val(),
                },
                success: function (data) {
                    if (data.status) {
                        $('#add-confirm').attr('class', 'btn btn-success');
                        $('#add-confirm').text('正在添加..');
                        setTimeout(function () {
                            $('#add-Modal').modal('hide');
                            location.reload();
                        }, 1500);
                    } else {
                        $('#add-confirm').attr('class', 'btn btn-danger');
                        $('#add-confirm').text('添加失败');
                    }
                }
            });
        } else {
            $('#add-confirm').attr('class', 'btn btn-danger');
            $('#add-confirm').text('请完善信息后重试');
        }
    });
}

function edit_product() {
    var target_id = undefined;
    $('.edit-button').click(function () {
        var now_td = $(this).parent().parent().find('td');
        $('#edit-id').val(now_td.eq(0).text());
        $('#edit-name').val(now_td.eq(1).text());
        $('#edit-num').val(now_td.eq(2).text());
        $('#edit-price').val(now_td.eq(3).text());
        target_id = $(this).attr('uid');
        $('#edit-Modal').modal('show');
    })
    $('#edit-confirm').click(function () {
        if ($('#edit-name').val() != '' && $('#edit-price').val() != '' && $('#edit-image').val() != '' && $('#edit-num').val() != '' && target_id != undefined) {
            $.ajax({
                url: `/edit-product?id=${target_id}`,
                type: 'POST',
                dataType: 'JSON',
                data: {
                    name: $('#edit-name').val(),
                    price: $('#edit-price').val(),
                    image: $('#edit-image').val().substring($('#edit-image').val().lastIndexOf('\\') + 1,),
                    num: $('#edit-num').val(),
                },
                success: function (data) {
                    if (data.status) {
                        $('#edit-confirm').attr('class', 'btn btn-success');
                        $('#edit-confirm').text('更改成功，请稍后..');
                    } else {
                        $('#edit-confirm').attr('class', 'btn btn-danger');
                        $('#edit-confirm').text('更改失败');
                    }
                    setTimeout(function () {
                        location.reload();
                    }, 1500);
                }
            })
        } else {
            $('#edit-confirm').attr('class', 'btn btn-danger');
            $('#edit-confirm').text('请完善信息后重试');
        }
    })
}

function delete_product() {
    $('.delete-button').click(function () {
        $.ajax({
            url: `/delete-product?id=${$(this).attr('uid')}`,
            type: 'GET',
            dataType: 'JSON',
            success: function (data) {
                if (data.status) {
                    $(this).attr('class', 'btn btn-success');
                    $(this).text('正在删除..');
                    alert('删除成功');
                } else {
                    $(this).attr('class', 'btn btn-danger');
                    $(this).text('删除失败');
                }
                setTimeout(function () {
                    location.reload();
                }, 1500);   
            }
        })
    })
}

function select_product() {
    $('.select-button').click(function () {
        var now_td = $(this).parent().parent().find('td');
        $('#select-id').val(now_td.eq(0).text());
        $('#select-name').val(now_td.eq(1).text());
        $('#select-price').val(now_td.eq(2).text());
        $('#select-num').val(now_td.eq(3).text());
        $('#select-id').attr('readonly', 'readonly');
        $('#select-name').attr('readonly', 'readonly');
        $('#select-price').attr('readonly', 'readonly');
        $('#select-num').attr('readonly', 'readonly');
        $('#select-Modal').modal('show');
    });
}

function devise_product() {
    var spare_num = 1;
    $('#devise-button').click(function () {
        $('#devise-Modal').modal('show');
    });
    $('#add-spare-button').click(function () {
        if (spare_num < 10) {
            spare_num += 1;
            $new_spare_input_area = `
                <div class="row">
                    <div class="col-sm-2" style="padding-right: 0; text-align: left;"><label for="spare-${spare_num}"
                            style="padding-top: 8px; font-size: normal;">产品零件${spare_num}</label></div>
                    <div class="col-sm-5" style="padding-left: 0;">
                        <select id="spare-${spare_num}" class="form-control spare-list" name="gender">
                        </select>
                    </div>
                    <div class="col-sm-5" style="padding-left: 0;">
                        <input type="number" id="spare-${spare_num}-num" class="form-control" placeholder="零件数量" value="0">
                    </div>
                </div>
            `;
            $('#add-spare-area').append($new_spare_input_area);
            init_spare_list();
        }
    });
    $('#del-spare-button').click(function () {
        if (spare_num > 1) {
            $('#add-spare-area').find('div[class="row"]').eq(-1).remove();
            spare_num -= 1;
        }
    });
    $('#devise-confirm').click(function () {
        // if ($('#devise-name').val() != '' &&
        // $('#devise-size').val() != '' &&
        // $('#devise-color').val() != '' &&
        // $('#spare-1-num').val() != '' &&
        // $('#spare-2-num').val() != '' &&
        // $('#spare-3-num').val() != '' &&
        // $('#spare-4-num').val() != '' &&
        // $('#devise-image').val() != '') {
        //     $.ajax({
        //         url: '/devise-product',
        //         type: 'post',
        //         dataType: 'JSON',
        //         data: {
        //             name: $('#devise-name').val(),
        //             image: $('#devise-image').val().substring($('#devise-image').val().lastIndexOf('\\') + 1,),
        //             color: $('#devise-color').val(),
        //             size: $('#devise-size').val(),
        //             spare_1: $('#spare-1').val(),
        //             spare_2: $('#spare-2').val(),
        //             spare_3: $('#spare-3').val(),
        //             spare_4: $('#spare-4').val(),
        //             spare_1_num: $('#spare-1-num').val(),
        //             spare_2_num: $('#spare-2-num').val(),
        //             spare_3_num: $('#spare-3-num').val(),
        //             spare_4_num: $('#spare-4-num').val(),
        //         },
        //         success: function (data) {
        //             if (data.status) {
        //                 location.reload();
        //             } else {
        //                 alert('连接数据失败');
        //             }
        //         }
        //     });
        // } else {
        //     $('#devise-confirm').attr('class', 'btn btn-danger');
        //     $('#devise-confirm').text('请先完善信息');
        // }
        const baseSuggest = (info) => {
            switch(info) {
                case 1:
                    $('#devise-confirm').attr('class', 'btn btn-danger');
                    $('#devise-confirm').text('请先完善信息');
                    break;
                case 2:
                    $('#devise-confirm').attr('class', 'btn btn-danger');
                    $('#devise-confirm').text('数据连接失败');
                    break;
                default:
                    break;
            }
        };
        const makeDataDict = () => {
            res_dict = {
                spare_num: spare_num,
                name: $('#devise-name').val(),
                image: $('#devise-image').val().substring($('#devise-image').val().lastIndexOf('\\') + 1,),
                color: $('#devise-color').val(),
                size: $('#devise-size').val(),
            }
            for (var idx = 1; idx <= spare_num; idx += 1) {
                res_dict['spare_' + idx] = $('#spare-' + idx).val();
                res_dict['spare_' + idx + '_num'] = $('#spare-' + idx + '-num').val();
            }
            return res_dict;
        }
        const checkList = ['devise-name', 'devise-size', 'devise-color', 'devise-image'];
        if (hasEmptyIpt(checkList)) {
            baseSuggest(1);
        } else {
            var checkSpareList = [];
            for (var idx = 1; idx <= spare_num; idx += 1) {
                checkSpareList.push('spare-' + idx + '-num');
            }
            if (hasEmptyIpt(checkSpareList)) {
                baseSuggest(1);
            } else {
                $.ajax({
                    url: '/devise-product',
                    type: 'post',
                    dataType: 'JSON',
                    data: makeDataDict(),
                    success: function (data) {
                        if (data.status) {
                            location.reload();
                        } else {
                            baseSuggest(2);
                        }
                    }
                });
            }
        }
    });
}

function init_spare_list() {
    $option = `
        <option value="-1">无</option>
    `;
    $('.spare-list').empty();
    $('.spare-list').append($option);
    $.ajax({
        url: '/spares-list',
        type: 'get',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                var result = new Array(data.result);
                result.forEach((val, _idx, _arr) => {
                    val.forEach((sub_val, _sub_idx, _sub_arr) => {
                        $option = `
                            <option value="${sub_val['id']}">${sub_val['name']}</option>
                        `;
                        $('.spare-list').append($option);
                    });
                });
            } else {
                alert('数据获取失败');
            }
        }
    })
}

function onshop() {
    var target_id = undefined;
    $('.onshop-button').click(function () {
        target_id = $(this).attr('uid');
        $('#onshop-Modal').modal('show');
    });
    $('#on-shop-confirm').click(function () {
        if ($('#on-shop-price').val() != '') {
            $.ajax({
                url: `/on-shop?id=${target_id}`,
                type: 'post',
                dataType: 'json',
                data: {
                    price: $('#on-shop-price').val(),
                },
                success: function (data) {
                    if (data.status) {
                        location.reload();
                    } else {
                        alert('数据提交失败');
                    }
                }
            });
        } else {
            $('#on-shop-confirm').attr('class', 'btn btn-danger');
            $('#on-shop-confirm').text('请先完善信息');
        }
    })
}

function getoffshop() {
    $('.getoff-button').click(function () {
        var id = $(this).attr('uid');
        $.ajax({
            url: `/off-shop?id=${id}`,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    location.reload();
                } else {
                    alert('数据提交失败');
                }
            }
        });     
    });
}

function hasEmptyIpt(i_list) {
    var res = false;
    i_list.forEach((val, _idx, _arr) => {   
        if ($('#' + val).val() == '') res = true;
    });
    return res;
}